import { createRouter, createWebHistory } from "vue-router";
import Home from "../views/Home/index.vue";
import ClassIf from "../views/ClassIf/index.vue";
import ShopCart from "../views/ShopCart/index.vue";
import My from "../views/My/index.vue";
import Search from "../views/Search/index.vue";
import Login from "../views/Login/index.vue";
import Register from "../views/Register/index.vue";
import Code from "../views/Register/Code.vue";
import SetPass from "../views/Register/SetPass.vue";
import Detail from "@/views/Detail/index.vue";
import Category from "@/views/ClassIf/Category.vue";
import City from "@/views/City/City.vue";
import SearchGoods from '@/views/Search/SearchGoods.vue';
const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: "/",
      redirect: "/Home",
    },
    {
      path: "/Home",
      name: "Home",
      component: Home,
    },
    {
      path: "/ClassIf",
      name: "ClassIf",
      component: ClassIf,
    },
    {
      path: "/ShopCart",
      name: "ShopCart",
      component: ShopCart,
      meta: {
        requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
      },
    },
    {
      path: "/My",
      name: "My",
      component: My,
      meta: {
        requireAuth: true, // 添加该字段，表示进入这个路由是需要登录的
      },
    },
    {
      path: "/Search",
      name: "Search",
      component: Search,
    },
    {
      path: "/SearchGoods",
      name: "SearchGoods",
      component: SearchGoods,
    },
    {
      path: "/Login",
      name: "Login",
      component: Login,
    },
    {
      path: "/Register",
      name: "Register",
      component: Register,
    },
    {
      path: "/Code",
      name: "Code",
      component: Code,
    },
    {
      path: "/SetPass",
      name: "SetPass",
      component: SetPass,
    },
    {
      path: "/Detail/:id",
      name: "Detail",
      component: Detail,
    },
    {
      path: "/Category",
      name: "Category",
      component: Category,
    },
    {
      path: "/City",
      name: "City",
      component: City,
    },
  ],
});
// 使用 Vue Router 的 beforeEach 导航守卫函数
router.beforeEach((to, from, next) => {
  // 检查目标路由的元字段是否需要认证
  if (to.meta.requireAuth) {
    // 如果需要认证
    if (sessionStorage.getItem("token")) {
      // 如果会话存储中存在名为 "token" 的项，表示用户已通过身份验证
      // 允许继续导航到目标路由
      next();
    } else {
      // 如果会话存储中不存在名为 "token" 的项，表示用户未经身份验证
      // 重定向到登录页面，并传递要访问的目标路径作为查询参数
      next({
        path: "/Login",
        query: {
          path: to.path,
        },
      });
    }
  } else {
    // 如果不需要认证，直接允许导航到目标路由
    next();
  }
});

export default router;
